<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Message {
	
	//获取未读消息数量
    public function getUnreadAmt($userid) 
	{
		$CI = & get_instance();
		//var_dump($userid);
		$query = $CI->db->query("SELECT * FROM msg WHERE Msg_To = '$userid' AND IsDel = '0' AND IsRead = '0'");
		//var_dump($query);
		return $query->num_rows();
    }
	
	//获取未读消息列表
	public function getUnreadArray($userid)
	{
		$CI = & get_instance();
		$query = $CI->db->query("SELECT id,Msg_From AS 'from',Msg_To AS 'to',Msg_Content AS 'content',IsRead AS 'isread',time FROM msg WHERE Msg_To = '$userid' AND IsDel = '0' AND IsRead = '0' ORDER BY time DESC");
		$ret = array();
		foreach($query->result_array() as $row)
		{
			$ret[] = $row;
		}
		return $ret;
	}
	
	
	//id,Msg_From,Msg_To,Msg_Content,IsRead,time
	//获取所有消息
	public function getAllArray($userid)
	{
		$CI = & get_instance();
		$query = $CI->db->query("SELECT id,Msg_From AS 'from',Msg_To AS 'to',Msg_Content AS 'content',IsRead AS 'isread',time FROM msg WHERE Msg_To = '$userid' AND IsDel = '0' ORDER BY time DESC");
		$ret = array();
		foreach($query->result_array() as $row)
		{
			$ret[] = $row;
		}
		return $ret;
	}
	
	//发送消息，默认使用system用户名发送
	public function send($content,$to,$from = 'system')
	{
		$CI = & get_instance();
		$query = $CI->db->query("SELECT * FROM user WHERE User_ID = '$to'");
		if ($CI->db->affected_rows()==0) return false;
		$query = $CI->db->query("INSERT INTO msg (Msg_From,Msg_To,Msg_Content) VALUES('$from','$to','$content')");
		if ($CI->db->affected_rows()==1) return true;
		else return false;
	}
	
	//将消息标记为已读
	public function markAsRead($msgid)
	{
		$CI = & get_instance();
		$query = $CI->db->query("UPDATE msg SET IsRead = '1' WHERE id = $msgid");
		if ($CI->db->affected_rows()==1) return true;
		else return false;
	}
	
	//删除消息
	public function delete($msgId)
	{
		$CI = & get_instance();
		$query = $CI->db->query("DELETE FROM msg WHERE id = $msgId");
		if ($CI->db->affected_rows()==1) return true;
		else return false;
	}
	
}

// END Auth class

/* End of file Auth.php */
/* Location: ./php_application/libraries/Pages.php */